(function(pageName){
  sugarcane.module[pageName] = function(){
    $('.j-pagescreen').addClass('fn-hide');
    var urlParams = sugarcane.getUrlParams(),timeing = null, needlog = urlParams['needlog'], canvote = urlParams['canvote'], status = urlParams['status'],docType = 1,
      newsId = urlParams['newsId'],//此处的id是给客户端打开正确的新闻详情页
      voteId = urlParams['id'],optionId = urlParams['optionid'];

     if ($('#j-screen-'+pageName+voteId).length) {
      var pageScreen = $('#j-screen-'+pageName+voteId);
      pageScreen.removeClass('fn-hide');
      var _scrollTop = pageScreen.data('scrolltop') || 0;
      setTimeout(function(){
        $(window).scrollTop(_scrollTop);
      }, 10);
      return false;
    }



    var pageScreen = $('<div class="j-pagescreen" id="j-screen-'+pageName+voteId+'"></div>');
    pageScreen.css('background','#fff');
    $('body').append(pageScreen).css('background','#fff');

    var votedetailObj = `
      <div class="app-votedetail">
        <div class="header j-detailtitle">
        </div>
        <img class="dividline" src="/static/img/detailline.png">
        <div class="main">
          <div class="content j-detailcontent"></div>
        </div>
        <div class="footer">
          <span class="j-votebtn btn btn-block ">投TA一票</span>
        </div>
      </div>
    `;

    pageScreen.append(votedetailObj);

    votedetailShow();
    function votedetailShow(){
      sugarcane.ajaxApi({
        "url": "/interactive/voteOptionDetail",
        "data": {"id": optionId,"newsId": newsId},
        "callback": function(res){
          if (res['code'] == 0) {
            sugarcane.twoShare({
              "id": res.data.id,
              "title": res.data.title,
              "desc": '分享来自经济日报客户端，更多精彩请下载http://d.jingjiribao.cn/index.html',
              "imgUrl": res.data.shareImage,
              "link": res.data.shareUrl,
              "docType": res.data.docType
            });
            document.title = res['data']['title'];
            status = res.data.interactiveStatus;
            canvote = res.data.canVote;
            if(res.data.docType){
              docType = res.data.docType;
            }
            pageScreen.find('.j-detailtitle').html(res.data.option);
            var newscontentObj = newGrapes["newscontent"].init({"content": res.data.description});
            // 处理编辑携带的字体大小
            // newscontentObj.find('p').css("font-size", "inherit").css('line-height',"inherit");

            // 处理编辑携带的字体大小，按屏幕大小等比显示，还有行高
            newscontentObj.find('*').each(function(){
              var _fontSize = this.style.fontSize,
                _lineHeight = this.style.lineHeight;
              if (_fontSize) {
                _fontSize = _fontSize.toLowerCase();
                if (_fontSize.indexOf('px') > -1) {
                  _fontSize = (_fontSize.replace('px', '') * pageScreen.width() / 375) + 'px';
                  $(this).css('font-size', _fontSize);
                }
              }
              if (_lineHeight) {
                _lineHeight = _lineHeight.toLowerCase();
                if (_lineHeight.indexOf('px') > -1) {
                  _lineHeight = (_lineHeight.replace('px', '') * pageScreen.width() / 375) + 'px';
                  $(this).css('line-height', _lineHeight);
                }
              }
            });
            // 处理图片大小
            newscontentObj.find('img').each(function(){
              var _width = $(this).attr('width'),
                _height = $(this).attr('height');
              if (_width) {
                _width = _width.replace('px', '') * pageScreen.width() / 375;
                $(this).attr('width', _width);
              }
              if (_height) {
                _height = _height.replace('px', '') * pageScreen.width() / 375;
                $(this).attr('width', _height);
              }
            });

            // 设置字体大小
            pageScreen.addClass('app-fontsize-' + sugarcane['app']['fontSize']);

            // 无图模式
            if (sugarcane['app']['appNopic']) {
              newscontentObj.find('img').remove();
            }

            pageScreen.find('.j-detailcontent').append(newscontentObj);

            if (!sugarcane['app']['isShare']) {
              formatContent(newscontentObj);
            }else{
              //video视频比列 16：9临时处理
              newscontentObj.find('video').each(function(i,o){
                if($(o).attr('height')){
                  $(o).attr('height','');
                  $(o).css('height','5.38rem');
                }else{
                  $(o).css('height','5.38rem');
                }
              }); 
            }

            if(status == '1'){
              pageScreen.find('.j-votebtn').text('暂未开始').addClass('forbidbtn');
            }else if(status == '2'){
              if(canvote == 0){
                pageScreen.find('.j-votebtn').text('感谢支持').removeClass('j-votebtn').addClass('outbtn');
              }else{
                pageScreen.find('.j-votebtn').text('投TA一票');
              }
            }else if(status == '3'){
              pageScreen.find('.j-votebtn').text('活动结束').addClass('forbidbtn');
            }

            pageScreen.find('.j-votebtn').click(function(){
              var _this = this;
              if(status == '1'){
                peach.toast('活动暂未开始');
              }else if(status == '2'){
                submitVote(optionId, needlog,function(res){
                  peach.toast(res.message);
                  if(res.data == false){//投票达到上限
                    $(_this).text('感谢支持').removeClass('j-votebtn').addClass('outbtn');
                  }


                });
              }else if(status == '3'){
                peach.toast('活动已结束');
              }
            });

            if(sugarcane['app']['isShare']){
              if(sugarcane['app']['isShare'] && !pageScreen.find('.app-banner').length ){
                sugarcane.module.load('banner', function(listitemFn){
                  var bannerObj = listitemFn({'id':newsId,'docType': docType});
                  pageScreen.append(bannerObj);
                  var _height = $(bannerObj).height() + parseInt(pageScreen.find('.main').css('margin-bottom').slice(0,-2));
                  pageScreen.find('.footer').css('margin-bottom',$(bannerObj).height()+'px');
                  pageScreen.find('.main').css('margin-bottom',_height+'px');
                });

              }
            }
          }else{
            showerrorView();
            peach.hiddenAppbar();
          }
        }
      });
    }

    function formatPoster(poster, width, height, callback){
      var newImg = new Image();
      newImg.src = poster;
      if (newImg.complete) {
        if ((width / height) > (newImg.width / newImg.height)) {
          newImg.style.height = height;
        } else {
          var _height = width * newImg.height / newImg.width;
          newImg.style.width = width;
          newImg.style.marginTop = ( newImg.height - _height) / 2;
          // newImg.style.marginTop = (height - _format['height']) / 2;
        }
        callback(newImg);
        // newObj.find('.poster').html(newImg);
      } else {
        newImg.onload = function () {
          if ((width / height) > (newImg.width / newImg.height)) {
            newImg.style.height = height;
          } else {
            var _height = width * newImg.height / newImg.width;
            newImg.style.width = width;
            newImg.style.marginTop = ( newImg.height - _height) / 2;
            // newImg.style.marginTop = (height - _format['height']) / 2;
          }
          callback(newImg);
          // newObj.find('.poster').html(newImg);
        };
        newImg.onerror = function (error) {
          // console.log(error);
        };
      }
    }
    // 处理内容
    function formatContent(contentObj){
      // 处理 a 标签
      contentObj.find('a').each(function(){
        $(this).data('href', $(this).attr('href'));
        $(this).attr('href','javascript:void(0)');
        $(this).on(tap, function(){
          peach.openUrl($(this).data('href'));
        });
      });
      // 处理 img 标签
      var imgList = [];
      contentObj.find('img').each(function(index){
        $(this).data('index', index);
        imgList.push({'imgUrl': $(this).attr('src'),'imgTitle': $(this).attr('title') || $(this).attr('alt') || ''});
      });
      contentObj.find('img').on(tap, function(){
        peach.previewImage({
          'index': $(this).data('index'),
          'imgList': imgList
        });
      });
      // 处理 video 标签
      // contentObj.find('video').each(function(){
      //   var newObj = $('<div><div class="play"></div><div class="poster"></div></div>');
      //   if ($(this).hasClass('vr-video') || $(this).hasClass('vr')) {
      //     newObj.addClass('app-vr');
      //   } else {
      //     newObj.addClass('app-video');
      //   }
      //   var width = $(this).width(),
      //     height = $(this).height(),
      //     poster = $(this).attr('poster') || '';
      //   // newObj.width(width);
      //   newObj.height(height);
      //   // if (poster) newObj.find('.poster').html('<img src="'+poster+'">');
      //   newObj.data('poster', poster);
      //   newObj.data('src', $(this).attr('src') || '');
      //   $(this).before(newObj);
      //   $(this).remove();
      //   // poster
      //   if (poster) {
      //     formatPoster(poster, width, height, function(posterImg){
      //       newObj.find('.poster').html(posterImg);
      //     });
      //   }
      // });
       // 处理 video 标签
      contentObj.find('video').each(function(){
        var newObj = $('<div class=""><div class="play"><img src="/static/img/playbtn.png" style="width:100%;"></div><div class="poster"></div></div>');
        if ($(this).hasClass('vr-video') || $(this).hasClass('vr')) {
          newObj.addClass('app-vr');
        } else {
          newObj.addClass('app-video');
        }

        var width = $(this).width(),
          height = $(this).width() *9/16,
          poster = $(this).attr('poster') || '';
        newObj.data('poster', poster);
        newObj.data('src', $(this).attr('src') || '');
        $(this).before(newObj);
        $(this).remove();
        // poster
        if (poster) {
          formatPoster(poster, width, height, function(posterImg){
            newObj.find('.poster').html(posterImg);
          });
        }
      });
      contentObj.find('.app-vr').on(tap, function(){
        peach.playVrFull($(this).data('src'));
      });
      contentObj.find('.app-video').on(tap, function(){
        var offset = $(this).offset();
        peach.playVideo({
          'url': $(this).data('src'),
          'poster': $(this).data('poster'),
          'offsetX': offset['left'],
          'offsetY': offset['top'],
          'width': offset['width'],
          'height': offset['height']
        });
      });
    }

    function submitVote(id, needlogin, callback){
      if (sugarcane['app']['isShare']) {
        // 去下载
        sugarcane['openApp']({'id':newsId,'docType': docType});
      } else {
        if(needlog == '1'){//需要登录
          if (sugarcane['app']['userId']) {
            sugarcane.ajaxApi({
              "url": "/interactive/vote",
              "data": {"id": voteId,'optionId': id},
              "callback": function(res){
                if(res.code == 0){
                  callback(res);
                }else{
                  peach.toast(res.message);
                }
              }
            });
          }else{
            // 去登录
            peach.login({
              'success': function(userInfo){
                sugarcane['app']['userId'] = userInfo['userId'];
              }
            });
          }
        }else{
          sugarcane.ajaxApi({
            "url": "/interactive/vote",
            "data": {"id": voteId,'optionId': id},
            "callback": function(res){
              if(res.code == 0){
                callback(res);
              }else{
                peach.toast(res.message);
              }
            }
          });
        }
      }
    }

    function showerrorView(){
      var clientHeight = document.documentElement.clientHeight;
      pageScreen.css('position','relative').css('height',clientHeight+'px');
      var errorviewObj = $(`<div class="app-errorview">
          <img class="img" src="/static/img/isempty.png">
        <p class="error-tip">暂时没有数据</p>
      </div>`);
       pageScreen.append(errorviewObj);
    }

  }
  sugarcane.module['state'][pageName] = 'load';
  sugarcane.module.callback(pageName);
}('votedetail'));